<template>
    <div>
      <!-- 面包屑导航区 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/admin/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>修改商品</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 卡片视图区域 -->
      <el-card>
          <!-- 提示区域 -->
          <el-alert title="修改商品信息" type="info" center show-icon :closable="false">
          </el-alert>
          <!-- 步骤条区域 -->
          <el-steps :space="200" :active="activeIndex - 0" align-center finish-status="success">
              <el-step title="基本信息"></el-step>
              <!-- <el-step title="商品参数"></el-step>
              <el-step title="商品属性"></el-step> -->
              <el-step title="商品图片"></el-step>
              <el-step title="商品内容"></el-step>
              <el-step title="完成"></el-step>
          </el-steps>
          <!-- tab栏 -->
          <el-form :model="addFrom" :rules="addFromRules" ref="addFromRef" label-width="100px" label-position="top">
            <el-tabs v-model="activeIndex" :tab-position="'left'"
            :before-leave="beforeTabLeave">
              <el-tab-pane label="基本信息" name="0">
                <el-form-item label="商品名称" prop="name">
                  <el-input v-model="addFrom.name"></el-input>
                </el-form-item>
                <el-form-item label="商品价格" prop="price">
                  <el-input type="number" v-model="addFrom.price"></el-input>
                </el-form-item>
                <el-form-item label="商品重量" prop="weight">
                  <el-input type="number" v-model="addFrom.weight"></el-input>
                </el-form-item>
                <el-form-item label="商品数量" prop="number">
                  <el-input type="number" v-model="addFrom.number"></el-input>
                </el-form-item>
                <el-form-item label="商品分类" prop="cate">
                  <el-cascader
                    v-model="addFrom.cateId"
                    :options="catelist"
                    :props="{ expandTrigger: 'hover',
                              label: 'name',
                              value: 'id',
                              children: 'children' }"
                    @change="handleChange"></el-cascader>
                </el-form-item>
              </el-tab-pane>
              <!-- <el-tab-pane label="商品参数" name="1">商品参数</el-tab-pane>
              <el-tab-pane label="商品属性" name="2">商品属性</el-tab-pane> -->
              <el-tab-pane label="商品图片" name="1">
                <!-- action: 图片要上传到的后台API地址 -->
                <el-upload
                  action="http://localhost:8888/product/upload"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  list-type="picture"
                  :headers="headerObj"
                  :on-success="handleSuccess"
                  accept="image/jpeg,image/jpg,image/png">
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过5M</div>
                </el-upload>
              </el-tab-pane>
              <el-tab-pane label="商品内容" name="2">
                <!-- 富文本编辑器 -->
                <quill-editor v-model="addFrom.description"></quill-editor>
                <!-- 添加商品的按钮 -->
                <el-button type="primary" class="btuAdd" @click="add">提 交 修 改</el-button>
              </el-tab-pane>
            </el-tabs>
          </el-form>
      </el-card>
      <!-- 图片预览 -->
      <el-dialog
        title="图片预览"
        :visible.sync="previewVisible"
        width="50%">
        <el-image :src="previewPath"></el-image>
      </el-dialog>
    </div>
  </template>
  <script>
  import _ from 'lodash'
  export default {
      data() {
          return {
              activeIndex: 0,
              // 添加商品的表单数据对象
              addFrom: {
                name: '宠物名字',
                price: 110,
                weight: 1110,
                number: 1110,
                // 商品所属分类数组
                cateId: [],
                // 图片的数组
                picture: [],
                // 商品的详情描述
                description: ''
              },
              addFromRules: {
                name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
                price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
                weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }],
                number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
                cateId: [{ required: true, message: '请选择商品分类', trigger: 'blur' }]
              },
              // 商品分类列表
              catelist: [],
              // 上传图片的URL地址
              uploadURL: 'http://localhost:8888/upload',
              // 图片上传组件的headers请求头
              headerObj: {
                Authorization: window.sessionStorage.getItem('token')
              },
              previewPath: '',
              previewVisible: false
          }
      },
      created() {
        this.getCateList()
        // 获取商品数据
        this.addFrom = this.$route.query.product
      },
      methods: {
        // 获取商品分类数据
        async getCateList() {
          const { data: res } = await this.$axios.get('/product-categories/selectProduct',
          { params: { type: 2 } })
          if (res.code !== 200) {
            return this.$message.error('获取商品分类数据失败')
          }
          this.catelist = res.data.prolist
        },
        // 级联选择器选中选项变化，会触发这个函数
        handleChange() {
          console.log(this.addFrom.cateId)
        //   if (this.addFrom.cateId.length !== 2) {
        //     this.addFrom.cateId = []
        //   }
        },
        beforeTabLeave(activeName, oldActiveName) {
            // console.log(activeName)
            // console.log(this.addFrom.cateId)
        //   if (oldActiveName === '0' && this.addFrom.cateId.length !== 2) {
        //     this.$message.error('请先选择商品分类 ')
        //     return false
        //   }
        },
        // 处理图片预览效果
        handlePreview(file) {
          console.log(file)
          this.previewPath = file.response.data.url
          this.previewVisible = true
        },
        // 处理移除图片的操作
        handleRemove(file) {
          console.log(file)
          // 获取图片的临时路径
          const filePath = file.response.data.tmp_path
          // 从pics数组中，找到这个图片对应的索引值
          const i = this.addFrom.picture.findIndex(x => x.picture === filePath)
          // 调用splice方法，把图片信息对象，从pics数组中移除
          this.addFrom.picture.splice(i, 1)
          console.log(this.addFrom)
        },
        // 监听图片上传成功的事件
        handleSuccess(response, file, fileList) {
          console.log(file + '图片数据：' + response)
          // 拼接得到一个图片信息对象
          const picInfo = { picture: response.data.tmp_path, pictureUrl: response.data.url }
          this.addFrom.picture.push(picInfo)
          console.log(this.addFrom)
        },
        add() {
          this.$refs.addFromRef.validate(async valid => {
            if (!valid) {
              return this.$message.error('请填写必要的表单项')
            }
            const form = _.cloneDeep(this.addFrom)
            // 执行添加的业务逻辑
            if (this.addFrom.cateId.length === 2) {
                form.cateId = this.addFrom.cateId[1]
            } else {
                form.cateId = this.addFrom.cateId
            }
            console.log(form)
            const { data: res } = await this.$axios.put('/product/update/' + form.id, form)
            console.log(res)
            if (res.code !== 200) {
              return this.$message.error('添加失败')
            }
            this.$message.success('添加成功')
            this.$router.push('/merchant-home/product')
          })
        }
      }
  }
  </script>
  <style lang="less" scoped>
  .btuAdd {
    margin-top: 15px;
  }
  </style>
